#! /usr/bin/env python3.1

#import the simple server 
from wsgiref.simple_server import make_server
from wsgiref.util import *
from urllib.parse import urlparse

#gets t
def get_file(path):
	r = ''
	if path == '/':
		file = 'portal/index.html'
	else:
		file = path+'.html'
	try:		
		with open(file) as page:
			template = page.read()
			template = "html = ""'''"+template+"'''"
			template = template.replace(']]',"'''")
			template = template.replace('[[',"html += '''")
	except:
		with open('portal/index.html') as page:
			template = page.read()
			template = "html = ""'''"+template+"'''"
			template = template.replace(']]',"'''")
			template = template.replace('[[',"html += '''")
	#file = file.replace('/','_')
	#file ='tmp/'+file+'.py'
	#with open(file,'w') as code:
	#	code.write(template)
	#with open (file) as code:
	global html
	exec(template,globals())
	r = str.encode(html)
	return r
			




# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style envrironment variables and the
# second variable is the callable object (see PEP333)

def pyhp(environ, start_response):
	status = b'200 OK' # HTTP Status
	headers = [('Content-type', 'text/html; charset=utf-8')] # HTTP Headers
	start_response(status, headers)
	# The returned object is going to be printed
	s = request_uri(environ)
	url = urlparse(s)
	path = url.path
	r = get_file(path)
	return [r]



httpd = make_server('', 8000, pyhp)
print("Serving on port 8000...")

# Serve until process is killed
httpd.serve_forever()
